<template>
  <div :class="className" :style="{height:height,width:width}" />
</template>

<script>
import echarts from 'echarts'
// 引入饼状图组件
require('echarts/lib/chart/bar');  // 引入柱状图组件
require('echarts/theme/macarons') // echarts theme
import resize from './mixins/resize'

const animationDuration = 3000

export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '400px'
    },
    dataJson: Array,
    dataJsonName: Array
  },
  data() {
    return {
      chart: null,
    }
  },
  watch: {
    dataJson(newval, oldval) {
      this.dataJson = newval
      this.initChart()
    },
    dataJsonName(newval, oldval) {
      this.dataJsonName = newval
      this.initChart()
    }
  },
  mounted() {
    setTimeout(()=>{
      this.initChart()
    }, 500)
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$el, 'macarons')
      this.chart.setOption({
        title: {
          text: '客单价走势',
          subtext: '客单价走势',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            label: {
              backgroundColor: '#6a7985'
            }
          }
        },
        xAxis: {
          type: 'category',
          name: '天',
          data: this.dataJsonName
        },
        yAxis: {
          type: 'value',
          name: '金额（人民币）'
        },
        series: [{
          data: this.dataJson,
          type: 'bar',
          showBackground: true,
          backgroundStyle: {
            color: 'rgba(220, 220, 220, 0.8)',
            borderWidth: 2
          },
          barGap: "31%",
          animationDuration: animationDuration
        }]
      })
    }
  }
}
</script>
